package com.ecode.imecode;

import com.alibaba.fastjson.JSONObject;
import com.ecode.imecode.pack.MessagePack;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * 数据字符编码器 <需要编码的类型>
 */
public class MessageEncode extends MessageToByteEncoder<MessagePack> {

    private String chartSet;

    public MessageEncode(String chartSet) {
        this.chartSet = chartSet;
    }


    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, MessagePack messagePack,
                          ByteBuf byteBuf) throws Exception {
        Object data = messagePack.getData();
        String datsStr = JSONObject.toJSONString(data);
        byteBuf.writeInt(messagePack.getCommand());
        byteBuf.writeInt(datsStr.length());
        byteBuf.writeBytes(datsStr.getBytes(chartSet));
    }
}
